/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011      Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
 
http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lua;

import java.util.ArrayList;
import java.util.List;

import org.cocos2dx.bean.GameData;
import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxLuaJavaBridge;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

import com.weibo.game.sdk.WeiboGameSDKAPI;
import com.weibo.game.sdk.callback.SinaUser;

/**
 * 游戏的MainActivity
 * 
 * 说明：为了演示方便，该游戏里使用了第三方数据存储服务sdk（BMob），用来保存游戏数据，实际开发中使用自己服务器即可
 * 新浪sdk自身不依赖BMob sdk，所以libs目录下的BMobSDK是用作存储数据演示用的，请无视这个jar包以及BMob相关代码
 * 
 * @author ye
 */
public class AppActivity extends Cocos2dxActivity{
	private static final String TAG = "AppActivity";
	
    public static final int START = 0;
    public static final int SUCESS = 1;
    public static final int ERROR = 2;
    public static final int CANCEL = 3;
    
	public static AppActivity s_instance;
	public Handler mHandler = new Handler();
	private ProgressDialog mProgressDialog;
	private SinaUser mSinaUser;
	
	/**BMob数据库存储相关*/
	private GameData mGameData;

    static String hostIPAdress = "0.0.0.0";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	//初始化微博sdk，必须在onCreate之前调用
    	WeiboGameSDKAPI.init(this);
        super.onCreate(savedInstanceState);
        
        // 初始化 Bmob SDK，跟新浪sdk接入流程无关，请无视
        Bmob.initialize(this, "7f7a694a6a78ffa2d601ebbb29944257");
        
        s_instance = this;
        mProgressDialog = new ProgressDialog(this);
        
        if(nativeIsLandScape()) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
        }
        
        //2.Set the format of window
        
        // Check the wifi is opened when the native is debug.
        if(nativeIsDebug())
        {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            if(!isNetworkConnected())
            {
                AlertDialog.Builder builder=new AlertDialog.Builder(this);
                builder.setTitle("Warning");
                builder.setMessage("Please open WIFI for debuging...");
                builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
                    
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                        finish();
                        System.exit(0);
                    }
                });

                builder.setNegativeButton("Cancel", null);
                builder.setCancelable(true);
                builder.show();
            }
            hostIPAdress = getHostIpAddress();
        }
    }
    private boolean isNetworkConnected() {
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);  
            if (cm != null) {  
                NetworkInfo networkInfo = cm.getActiveNetworkInfo();  
            ArrayList networkTypes = new ArrayList();
            networkTypes.add(ConnectivityManager.TYPE_WIFI);
            try {
                networkTypes.add(ConnectivityManager.class.getDeclaredField("TYPE_ETHERNET").getInt(null));
            } catch (NoSuchFieldException nsfe) {
            }
            catch (IllegalAccessException iae) {
                throw new RuntimeException(iae);
            }
            if (networkInfo != null && networkTypes.contains(networkInfo.getType())) {
                    return true;  
                }  
            }  
            return false;  
        } 
     
    public String getHostIpAddress() {
        WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
        int ip = wifiInfo.getIpAddress();
        return ((ip & 0xFF) + "." + ((ip >>>= 8) & 0xFF) + "." + ((ip >>>= 8) & 0xFF) + "." + ((ip >>>= 8) & 0xFF));
    }
    
    public static String getLocalIpAddress() {
        return hostIPAdress;
    }
    
    private static native boolean nativeIsLandScape();
    private static native boolean nativeIsDebug(); 
    
    //跟新浪sdk接入流程无关，请无视
    public void requestBmodGameUser(final String suid, final int luaFunc){
    	Log.d(TAG, "requestBmodGameUser(), suid = " + suid);
    	showProgressDialog(true);
    	//用BMob服务模拟游戏服务器-从服务器获取游戏数据
    	BmobQuery<GameData> query = new BmobQuery<GameData>();
    	query.addWhereEqualTo(BMobConstant.TABLE_KEY_SUID, suid);
    	query.findObjects(AppActivity.this, new FindListener<GameData>() {
			@Override
			public void onSuccess(List<GameData> result) {
				if (result != null && result.size() > 0) {
					//游戏服务器取到了玩家数据
					mGameData = result.get(0);
					//临时代码，防止用户从“新浪游客”绑定微博或手机成功后，游戏数据库里的用户名没有更新的问题
					if (mGameData != null && mSinaUser != null) {
						//使用新浪sdk的用户名
						mGameData.setUserName(mSinaUser.getUserName());
					}
					//通知客户端
					notifyGame(mGameData, luaFunc);
					showProgressDialog(false);
				}else{
					//游戏服务器没有玩家数据，插入新的数据
					bmobInsertGameData(suid, luaFunc);
				}
			}
			
			@Override
			public void onError(int code, String error) {
				Log.w(TAG, "bmobQueryGameData-onError() : " + "code = " + code + ", error: " + error);
				Toast.makeText(AppActivity.this, "code = " + code + ", error: " + error, Toast.LENGTH_LONG).show();
				bmobInsertGameData(suid, luaFunc);
				Cocos2dxLuaJavaBridge.releaseLuaFunction(luaFunc);
				showProgressDialog(false);
			}
		});
    }
    
    //跟新浪sdk接入流程无关，请无视
    public void bmobInsertGameData(String suid, final int luaFunc){
    	Log.d(TAG, "bmobInsertGameData()");
    	final GameData data = new GameData();
    	data.setSuid(suid);
    	if (mSinaUser != null) {
    		data.setUserName(mSinaUser.getUserName());
    	}
    	data.setGold(0);
    	data.setHighScore(0);
    	data.setTableName(BMobConstant.TABLE_NAME_GAME_DATA);
    	data.save(AppActivity.this, new SaveListener() {
			@Override
			public void onSuccess() {
				Log.d(TAG, "插入新的gameData成功！");
				//通知客户端
				mGameData = data;
				notifyGame(mGameData, luaFunc);
				showProgressDialog(false);
			}
			
			@Override
			public void onFailure(int code, String error) {
				Log.d(TAG, "插入新的gameData失败！ code: " + code + ", error: " + error);
				Cocos2dxLuaJavaBridge.releaseLuaFunction(luaFunc);
				showProgressDialog(false);
			}
		});
    }
    
    //跟新浪sdk接入流程无关，请无视
    private String generateGameDataStr(GameData data){
    	StringBuffer sb = new StringBuffer();
    	sb.append(data.getSuid()).append("|")
    	.append(data.getUserName()).append("|")
    	.append(data.getGold()).append("|")
    	.append(data.getHighScore());
    	
    	return sb.toString();
    }
    
    //传递数据给lua端
    private void notifyGame(final GameData data, final int luaFunc){
    	Log.d(TAG, "notifyGame()");
        AppActivity.s_instance.runOnGLThread(new Runnable() {
            @Override
            public void run() {
            	//此处为了演示方便，直接将userName传给lua了，实际游戏里可以将json数据传给lua
            	String result = generateGameDataStr(data);
            	Log.d(TAG, "notifyGame: " + result);
                Cocos2dxLuaJavaBridge.callLuaFunctionWithString(luaFunc, result);
                Cocos2dxLuaJavaBridge.releaseLuaFunction(luaFunc);
            }
        });
    }
    
    public void setSinaUser(SinaUser sinaUser){
    	mSinaUser = sinaUser;
    }
    
    public SinaUser getSinaUser(){
    	return mSinaUser;
    }
    
    //跟新浪sdk接入流程无关，请无视
    public void setGameData(GameData gameData){
    	mGameData = gameData;
    }
    
    //跟新浪sdk接入流程无关，请无视
    public GameData getGameData(){
    	return mGameData;
    }
    
    public void showProgressDialog(final boolean show){
    	if (this.isFinishing()) {
    		return;
    	}
    	
		runOnUiThread(new Runnable() {
            @Override
            public void run() {
        		if (show) {
        			if (!mProgressDialog.isShowing()) {
        				mProgressDialog.show();
        			}
        		}else{
        			mProgressDialog.dismiss();
        		}
            }
        });
    }
    
    @Override
    protected void onPause() {
    	super.onPause();
    	
    	//不让onPause执行，处理用户按锁屏键后再恢复，游戏黑屏的问题
    	onResume();
    }
    
    public void toastShort(final String text){
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
            	Toast.makeText(AppActivity.this, text, Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    public void toastLong(final String text){
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
            	Toast.makeText(AppActivity.this, text, Toast.LENGTH_LONG).show();
            }
        });
    }
}
